import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

// 用户权限接口
export interface Permission {
  userId: number;
  permissionKey: string; // 页面路径或操作标识（如 '/material-manage' 或 'feedback_reply'）
}

// 用户信息接口（简化为权限管理需要字段）
export interface User {
  id: number;
  username: string;
  role: string;
}

// 权限管理表单数据
export interface PermissionForm {
  userId: number;
  permissions: string[];
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    permissions: {} as Record<number, string[]>,
    users: [] as User[],
  }),
  actions: {
    // 获取所有权限
    async fetchPermissions() {
      try {
        const response = await axios.get('/permissions');
        if (response.data.code === 200) {
          // 将权限列表转换为用户ID到权限数组的映射
          const perms = response.data.data as Permission[];
          this.permissions = perms.reduce((acc, perm) => {
            if (!acc[perm.userId]) acc[perm.userId] = [];
            acc[perm.userId].push(perm.permissionKey);
            return acc;
          }, {} as Record<number, string[]>);
          console.log('Store: Fetched permissions:', this.permissions);
          return this.permissions;
        }
        throw new Error(response.data.message || '获取权限列表失败');
      } catch (error: any) {
        console.error('Store: 获取权限列表失败:', error);
        ElMessage.error(error.response?.data?.message || '网络错误，无法获取权限列表');
        return {};
      }
    },

    // 更新用户权限
    async updatePermissions(form: PermissionForm) {
      try {
        const response = await axios.put('/permissions', form);
        if (response.data.code === 200) {
          this.permissions[form.userId] = form.permissions;
          console.log('Store: Updated permissions for user', form.userId, ':', form.permissions);
          return response.data.data;
        }
        throw new Error(response.data.message || '更新权限失败');
      } catch (error: any) {
        console.error('Store: 更新权限失败:', error);
        ElMessage.error(error.response?.data?.message || '网络错误，无法更新权限');
        throw error;
      }
    },
  },
});